﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KeaoBase;
using KeaoMDS.AppCode;
using KeaoMDS.Weight;
using System.Diagnostics;
using GoldPrinter;

namespace KeaoMDS.Report
{
    public partial class TuiKuMingXi : BaseForm
    {

        private string m_ChengZhongLeiXing = string.Empty;

        public TuiKuMingXi(string ChengZhongLeiXing)
        {
            m_ChengZhongLeiXing = ChengZhongLeiXing;
            InitializeComponent();
        }

        private void TuiKuMingXi_Load(object sender, EventArgs e)
        {
            grid_mingxi.AutoGenerateColumns = false;
            this.MinimumSize = this.Size;
            dateTimePicker1.Value = DateTime.Today;
            dateTimePicker2.Value = dateTimePicker1.Value.AddHours(23).AddMinutes(59).AddSeconds(59);

            BindWuLiaoMingCheng();
            BindDanWeiMingCheng();

            BindInfo();
            this.Text = string.Format("{0}{1}", m_ChengZhongLeiXing, this.Text);
        }

        private void BindDanWeiMingCheng()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("danweileixing", DataValueCommonType.字符串, m_ChengZhongLeiXing == "入库物料" ? "入库单位" : "出库单位", "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("danweizhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_danwei", createCondition);
            DataRow newRow = Dt.NewRow();
            newRow["danweimingcheng"] = "—请选择—";
            newRow["id"] = "";
            Dt.Rows.InsertAt(newRow, 0);
            cmb_danweimingcheng.DisplayMember = "danweimingcheng";
            cmb_danweimingcheng.ValueMember = "id";
            cmb_danweimingcheng.DataSource = Dt;
        }

        private void BindWuLiaoMingCheng()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaoleixing", DataValueCommonType.字符串, m_ChengZhongLeiXing, "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("wuliaozhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_wuliao", createCondition);
            DataRow newRow = Dt.NewRow();
            newRow["wuliaomingcheng"] = "—请选择—";
            newRow["id"] = "";
            Dt.Rows.InsertAt(newRow, 0);
            cmb_wuliao.DisplayMember = "wuliaomingcheng";
            cmb_wuliao.ValueMember = "id";
            cmb_wuliao.DataSource = Dt;
        }

        private void BindXingHao()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaobianhao", DataValueCommonType.字符串, cmb_wuliao.SelectedValue.ToString(), "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_xinghao", createCondition);
            DataRow newRow = Dt.NewRow();
            newRow["xinghao"] = "—请选择—";
            newRow["id"] = "";
            Dt.Rows.InsertAt(newRow, 0);
            cmb_xinghao.DisplayMember = "xinghao";
            cmb_xinghao.ValueMember = "id";
            cmb_xinghao.DataSource = Dt;
        }

        private void cmb_wuliao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb_wuliao.SelectedIndex != 0)
            {
                BindXingHao();
            }
            else
            {
                cmb_xinghao.DataSource = null;
            }
        }

        private void BindInfo()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("tuikushijian", DataValueCommonType.日期时间, dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss"), dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
            if (cmb_danweimingcheng.SelectedIndex > 0)
            {
                createCondition += KeaoUtils._DB.CreateAndCondition("tuikudanwei", DataValueCommonType.字符串, cmb_danweimingcheng.Text, "", SearchConditionType.等于);
            }
            if (cmb_wuliao.SelectedIndex > 0)
            {
                createCondition += KeaoUtils._DB.CreateAndCondition("tuikuwuliao", DataValueCommonType.字符串, cmb_wuliao.Text, "", SearchConditionType.等于);
            }
            if (cmb_xinghao.SelectedIndex > 0)
            {
                createCondition += KeaoUtils._DB.CreateAndCondition("tuikuxinghao", DataValueCommonType.字符串, cmb_xinghao.Text, "", SearchConditionType.等于);
            }
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                createCondition += KeaoUtils._DB.CreateAndCondition("tuikuchepaihao", DataValueCommonType.字符串, textBox1.Text, "", SearchConditionType.like);
            }
            createCondition += KeaoUtils._DB.CreateAndCondition("tuikuleixing", DataValueCommonType.字符串, m_ChengZhongLeiXing, "", SearchConditionType.等于);
            Dictionary<string, string> orderBy = new Dictionary<string, string>();
            orderBy.Add("tuikushijian", "desc");
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", createCondition,orderBy);
            DataTable DtCount = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", "count(id) as cheshu,sum(tuikumaozhong) as tuikumaozhong,sum(tuikupizhong) as tuikupizhong,sum(tuikujingzhong) as tuikujingzhong", null, createCondition, null, null);
            if (Dt.Rows.Count > 0)
            {
                DataRow newRow = Dt.NewRow();
                newRow["tuikuchepaihao"] = string.Format("合计：{0}车", DtCount.Rows[0]["cheshu"]);
                newRow["tuikumaozhong"] = DtCount.Rows[0]["tuikumaozhong"];
                newRow["tuikupizhong"] = DtCount.Rows[0]["tuikupizhong"];
                newRow["tuikujingzhong"] = DtCount.Rows[0]["tuikujingzhong"];
                Dt.Rows.Add(newRow);

            }
            grid_mingxi.DataSource = Dt;
            grid_mingxi.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BindInfo();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //导出报表
            DataTable Dt = grid_mingxi.DataSource as DataTable;
            if (Dt == null)
            {
                return;
            }
            if (m_ChengZhongLeiXing == "入库物料")
            {
                ExcelAccess excelAccess = new ExcelAccess();
                try
                {
                    excelAccess.Open(Application.StartupPath + "\\Template\\入库物资退库明细.xls");
                    excelAccess.SetCellText(2, "A", string.Format("报表时间：{0}——{1}", dateTimePicker1.Value, dateTimePicker2.Value));
                    for (int i = 0; i < Dt.Rows.Count; i++)
                    {
                        excelAccess.SetCellText(i + 4, "A", string.Format("{0}", Dt.Rows[i]["tuikubianhao"]));
                        excelAccess.SetCellText(i + 4, "B", string.Format("{0}", Dt.Rows[i]["tuikuchepaihao"]));
                        excelAccess.SetCellText(i + 4, "C", string.Format("{0}", Dt.Rows[i]["tuikudanwei"]));
                        excelAccess.SetCellText(i + 4, "D", string.Format("{0}", Dt.Rows[i]["tuikuwuliao"]));
                        excelAccess.SetCellText(i + 4, "E", string.Format("{0}", Dt.Rows[i]["tuikuxinghao"]));
                        excelAccess.SetCellText(i + 4, "F", string.Format("{0}", Dt.Rows[i]["tuikushijian"]));
                        excelAccess.SetCellText(i + 4, "G", string.Format("{0}", Dt.Rows[i]["tuikujingzhong"]));
                    }

                    excelAccess.MergeCells(4 + Dt.Rows.Count, "A", 4 + Dt.Rows.Count, "G", true);
                    excelAccess.SetCellText(4 + Dt.Rows.Count, "A", string.Format("制表人：{0}    制表时间：{1}", KeaoUtils._CurrentUserRow["yonghuxingming"], DateTime.Now.ToString("yyyy-MM-dd HH:mm")));

                    Excel.Range r = excelAccess.GetRange(4, "A", Dt.Rows.Count + 3, "G");
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlLeft);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlRight);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlBottom);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideHorizontal);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideVertical);

                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        excelAccess.SaveAs(string.Format("{0}\\{1}.xls", fbd.SelectedPath, DateTime.Now.ToString("yyyyMMddHHmm")), true);
                        KeaoUtils.ShowInfoMessage("报表导出Excel成功。");
                        Process.Start(fbd.SelectedPath);
                    }

                }
                catch (Exception err)
                {
                    KeaoUtils.LogTxt(string.Format("入库物资退库明细报表导出失败。{0}", err.Message));
                }
                finally
                {
                    excelAccess.Close();
                }
            }
            else
            {
                ExcelAccess excelAccess = new ExcelAccess();
                try
                {
                    excelAccess.Open(Application.StartupPath + "\\Template\\出库物资退库明细.xls");
                    excelAccess.SetCellText(2, "A", string.Format("报表时间：{0}——{1}", dateTimePicker1.Value, dateTimePicker2.Value));
                    for (int i = 0; i < Dt.Rows.Count; i++)
                    {
                        excelAccess.SetCellText(i + 4, "A", string.Format("{0}", Dt.Rows[i]["tuikubianhao"]));
                        excelAccess.SetCellText(i + 4, "B", string.Format("{0}", Dt.Rows[i]["tuikuchepaihao"]));
                        excelAccess.SetCellText(i + 4, "C", string.Format("{0}", Dt.Rows[i]["tuikudanwei"]));
                        excelAccess.SetCellText(i + 4, "D", string.Format("{0}", Dt.Rows[i]["tuikuwuliao"]));
                        excelAccess.SetCellText(i + 4, "E", string.Format("{0}", Dt.Rows[i]["tuikuxinghao"]));
                        excelAccess.SetCellText(i + 4, "F", string.Format("{0}", Dt.Rows[i]["tuikushijian"]));
                        excelAccess.SetCellText(i + 4, "G", string.Format("{0}", Dt.Rows[i]["tuikujingzhong"]));
                        excelAccess.SetCellText(i + 4, "H", string.Format("{0}", Dt.Rows[i]["tuikubiaoduan"]));
                    }

                    excelAccess.MergeCells(4 + Dt.Rows.Count, "A", 4 + Dt.Rows.Count, "H", true);
                    excelAccess.SetCellText(4 + Dt.Rows.Count, "A", string.Format("制表人：{0}    制表时间：{1}", KeaoUtils._CurrentUserRow["yonghuxingming"], DateTime.Now.ToString("yyyy-MM-dd HH:mm")));

                    Excel.Range r = excelAccess.GetRange(4, "A", Dt.Rows.Count + 3, "H");
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlLeft);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlRight);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlBottom);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideHorizontal);
                    excelAccess.SetBordersEdge(r, GoldPrinter.ExcelConstants.BordersEdge.xlInsideVertical);

                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        excelAccess.SaveAs(string.Format("{0}\\{1}.xls", fbd.SelectedPath, DateTime.Now.ToString("yyyyMMddHHmm")), true);
                        KeaoUtils.ShowInfoMessage("报表导出Excel成功。");
                        Process.Start(fbd.SelectedPath);
                    }

                }
                catch (Exception err)
                {
                    KeaoUtils.LogTxt(string.Format("出库物资退库明细报表导出失败。{0}", err.Message));
                }
                finally
                {
                    excelAccess.Close();
                }
            }
        }

        private void contextMenu_1_xiugai_Click(object sender, EventArgs e)
        {
            if (!KeaoUtils._CurrentUserRow["juesequanxian"].ToString().Contains("退库操作"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有权限进行此操作。");
                return;
            }
            if (grid_mingxi.SelectedRows.Count > 0)
            {
                string tuiKuID = string.Format("{0}", grid_mingxi.SelectedRows[0].Cells["id"].Value);
                if (!string.IsNullOrEmpty(tuiKuID))
                {
                    ChengZhongTuiKu chengZhongTuiKu = new ChengZhongTuiKu(m_ChengZhongLeiXing, grid_mingxi.SelectedRows[0]);
                    chengZhongTuiKu.ShowDialog();
                    BindInfo();
                }
            }

        }

        private void contextMenu_1_shanchu_Click(object sender, EventArgs e)
        {
            if (!KeaoUtils._CurrentUserRow["juesequanxian"].ToString().Contains("退库操作"))
            {
                KeaoUtils.ShowInfoMessage("该用户没有权限进行此操作。");
                return;
            }
            if (grid_mingxi.SelectedRows.Count > 0)
            {
                string tuiKuID = string.Format("{0}", grid_mingxi.SelectedRows[0].Cells["id"].Value);
                if (!string.IsNullOrEmpty(tuiKuID))
                {
                    if (KeaoUtils.ShowQuestionMessage("确定要删除该退库信息吗？") == DialogResult.Yes)
                    {
                        TableRow delRow = new TableRow();
                        delRow.ID = tuiKuID;
                        delRow.TableName = "tbl_tuiku";
                        string tuiKuBianHao = string.Format("{0}", grid_mingxi.SelectedRows[0].Cells["tuikubianhao"].Value);
                        if (KeaoUtils._DB.DeleteRowByID(delRow)>0)
                        {
                            BindInfo();
                            MainForm.RiZhi(string.Format("{0}删除退库信息，退库单号：{1}", KeaoUtils._CurrentUserRow["yonghuxingming"], tuiKuBianHao));
                        }
                    }
                }
            }
        }

        private void contextMenu_1_bangdan_Click(object sender, EventArgs e)
        {
            if (KeaoUtils.ShowQuestionMessage("确定重新打印退库单吗？") == DialogResult.Yes)
            {
                if (grid_mingxi.SelectedRows.Count > 0)
                {
                    string tuiKuID = string.Format("{0}", grid_mingxi.SelectedRows[0].Cells["id"].Value);
                    if (!string.IsNullOrEmpty(tuiKuID))
                    {
                        KeaoPrinter.PrintTuiKu(tuiKuID);
                    }
                }
            }
        }

        private void grid_mingxi_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }
    }
}
